import ContentLayout from '@/layouts/ContentLayout'
import ArrayUtils from '@/utils/ArrayUtils'
import { DEAMEN_STATUS, PRIORUTY_LEVEL } from '@/consts/project'
import { Button, Space, Table, Modal, Form, Input, DatePicker, message, Tag } from 'antd'
import { useState } from 'react'
import styles from './style.less'
import { connect ,history} from 'umi';
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect';
import UserBrief from '@/components/UserBrief'
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
import { useEffect } from 'react'
import PriorityLevel from '../PriorityLevel'
import DemandDetail from './DemandDetail'
import ActionDropdown from '@/components/ActionDropdown';
import CheckActon from '../CheckActoin'
import { pageDemand,saveNewDemand } from '@/services/project/demand'



const DemandStatus = (props) => {
    const {
        status
    } = props

    if (status || status === 0) {
        return <Tag color={DEAMEN_STATUS[status]?.color}>{DEAMEN_STATUS[status]?.name}</Tag>
    }
    return (
        <Tag>/</Tag>
    )
}

const ProjectDemand = (props) => {

    const {
        projectId,
        dispatch,
        queryInitParams,
        routeParam,
        projectPermission,
    } = props;

    const [demandPageData, setDemandPageData] = useState(false);
    const [demandPageDataLoading, setDemandPageDataLoading] = useState(false);

    const [isNewDemandModalVisiable, setNewDemandModalVisiable] = useState(false)
    const [form] = Form.useForm();
    const [params, setParams] = useState({
        sortType: 2,
        pageSize:10,
        pageNum:1
    })
    const [permission, setPermission] = useState({})


    useEffect(() => {
        let initParam = {
            ...params,
            ...queryInitParams,
        }
        setParams(initParam)
        if (projectId && !routeParam.itemId) {
            queryDemandPage({
                ...initParam,
            })
        }
    }, [projectId])

    useEffect(() => {
        setPermission({
            ...projectPermission?.prod
        })
    }, [projectPermission])

    const showDemandDetail = (id) => {
        history.push(`/projects/${projectId}/demand/${id}`)
    }

    if (routeParam.tab !== 'demand') {
        return <></>;
    }

  

    const onQueryParamChange = (params) => {
        dispatch({
            type: 'queryParams/saveQueryParams',
            payload: {
                name: "demandPage",
                params: params
            }
        });
    }

    // useEffect(() => {
    //     const stateDemandId = props.location && props.location.state && props.location.state.demandId;
    //     if (stateDemandId) {
    //         // 显示指定的需求
    //         setSelectDemand({ id: stateDemandId })
    //         setShowDemanDetail(true)
    //         return
    //     }
    //     if (demandPageData && demandPageData.list && demandPageData.list.length > 0 && !selectDemand) {
    //         setSelectDemand(demandPageData.list[0])
    //         setShowDemanDetail(true)
    //     }
    // }, [demandPageData])

    const onParamChange = (param,doQuery) => {
        if (param && !param.pageNum) {
            param.pageNum = 1;
        }
        let newParams = { ...params, ...param }
        setParams(newParams)
        onQueryParamChange(newParams)
        if (doQuery) {
            queryDemandPage(newParams)
        }
    }

    const queryDemandPage = (queryParams) => {
        setDemandPageDataLoading(true)
        pageDemand(projectId, queryParams).then(({ data }) => {
            setDemandPageData(data)
            setDemandPageDataLoading(false)
        })
    }

    const onSaveNewDemand = async () => {
        const values = await form.validateFields()
        let data = {
            ...values,
        }
        if (data.planDate) {
            data.planStartDate = data.planDate[0].format('yyyy-MM-DD');
            data.planEndDate = data.planDate[1].format('yyyy-MM-DD');
        }
        data.planDate = null
        saveNewDemand(projectId,data).then(({success}) => {
            if (success) {
                setNewDemandModalVisiable(false)
                message.success("保存成功");
                queryDemandPage(params);
                form.resetFields();
            }
        })
    }

    const queryItems = [

        {
            name: "inStatus",
            label: "状态",
            isMain: true,
            type: "tagSelect",
            options: ArrayUtils.jsonToArray(DEAMEN_STATUS).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "likeName",
            label: "需求名称",
            span: 8,
            isMain: false,
            type: "input",
        },
        {
            name: "inPriorityLevel",
            label: "优先级",
            isMain: false,
            span: 8,
            type: "select",
            options: ArrayUtils.jsonToArray(PRIORUTY_LEVEL).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "inUserId",
            label: "负责人",
            span: 8,
            isMain: false,
            type: "userSelect",
        },
        {
            name: "inToUserId",
            label: "指派给",
            span: 8,
            isMain: false,
            type: "userSelect",
        },
        
    ]

    const actionHeader = [
        <ActionDropdown
            key="actions"
            status={params?.isArchived && "filter"}
            placement="bottomRight"
            actions={[
                <CheckActon
                    check={params?.isArchived === 1}
                    onChange={(value) => {
                        if (value) {
                            onParamChange({
                                isArchived: 1
                            }, true)
                        } else {
                            onParamChange({
                                isArchived: null
                            }, true)
                        }
                    }}
                    label={'查看归档数据'}
                />,
            ]}
        />,
        <Button type="primary" size="middle" onClick={() => {
            setNewDemandModalVisiable(true)
        }}>
            新增
        </Button>,
        ,
        <CheckActon
            check={params?.mySelection === 1}
            onChange={(value) => {
                if (value) {
                    onParamChange({
                        mySelection: 1
                    }, true)
                } else {
                    onParamChange({
                        mySelection: null
                    }, true)
                }
            }}
            label={'只看我的'}
        />
    ]

    const tableColumns = [
        {
            title: '项目名',
            dataIndex: 'name',
            key: 'name',
            fixed: 'left',
            ellipsis: true,
            sorter: (a, b) => a.name.localeCompare(b.name),
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: "10%",
            sorter: (a, b) => a.status - b.status,
            render: (text, record) => <DemandStatus status={record.status}></DemandStatus>,
        },
        {
            title: '优先级',
            dataIndex: 'priorityLevel',
            key: 'priorityLevel',
            width: "8%",
            sorter: (a, b) => a.priorityLevel - b.priorityLevel,
            render: (text, record) => <PriorityLevel priorityLevel={record.priorityLevel}></PriorityLevel>,
        },
        {
            title: '负责人',
            dataIndex: 'userId',
            key: 'userId',
            width: "100px",
            render: (text, record) => <UserBrief user={record.user}></UserBrief>,
        },
        {
            title: '指派人',
            dataIndex: 'toUserId',
            key: 'userId',
            width: "100px",
            render: (text, record) => record.toUser && <UserBrief user={record.toUser}></UserBrief>,
        },
        {
            title: '需求方',
            dataIndex: 'userId',
            key: 'demandSource',
            render: (text, record) => record.demandSource && record.demandSource.name,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            sorter: (a, b) => a.createTime.localeCompare(b.createTime),
            defaultSortOrder: 'descend'
        }
    ]

    const filterColumn = (tableColumns) => {
        return tableColumns;
    }

    if (routeParam.itemId) {
        return  <DemandDetail  projectId={projectId} projectPermission={projectPermission} demandId={routeParam.itemId}></DemandDetail>
    }

    return <>
        <ContentLayout
            queryItems={queryItems}
            actionHeader={actionHeader}
            queryInitParams={queryInitParams}
            onQueryChange={onParamChange}
            content={
                <Table
                    onChange={(pagination, filters, sorter) => {
                        onParamChange({
                            pageNum: pagination.pageSize === params.pageSize ? pagination.current : 1,
                            pageSize: pagination.pageSize
                        },true)
                    }}
                    columns={filterColumn(tableColumns)}
                    rowKey="id"
                    loading={demandPageDataLoading}
                    dataSource={demandPageData && demandPageData.list}
                    pagination={{
                        position: ["bottomCenter"],
                        showSizeChanger: true,
                        pageSize: params.pageSize || 10,
                        total: demandPageData && demandPageData.count,
                        current: demandPageData && demandPageData.pageNum,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total, range) => `总数： ${total} `
                    }}
                    size="small"
                    onRow={record => {
                        return {
                            onClick: () => {
                                showDemandDetail(record.id)
                            }
                        }
                    }}
                >
                </Table>
            }
        >
        </ContentLayout>
        <Modal
            visible={isNewDemandModalVisiable}
            closable
            title={"新增需求"}
            onCancel={() => {
                setNewDemandModalVisiable(false)
            }}
            onOk={() => {
                onSaveNewDemand();
            }}
            destroyOnClose
            okText={"确认"}
            cancelText={"取消"}
        >
            <Form
                form={form}
                labelAlign="right"
                labelCol={{ span: 4 }}
            >
                <FormItem
                    label={"名称"}
                    name="name"
                    rules={[
                        {
                            required: true,
                            message: "请输入名称",
                        },
                    ]}
                >
                    <Input placeholder={"请输入名称"} maxLength={20} ></Input>
                </FormItem>
                <FormItem
                    label={"负责人"}
                    name="userId"
                    rules={[
                        {
                            required: true,
                            message: "请选择负责人",
                        },
                    ]}
                >
                    <EnterpriseUserSelect projectId={projectId} ></EnterpriseUserSelect>
                </FormItem>
                <Form.Item name="planDate" label={"预计周期"}>
                    <RangePicker format="YYYY-MM-DD" />
                </Form.Item>
                <FormItem label={"描述"}
                    name="description"
                    rules={[
                        {
                            required: true,
                            message: "请输入描述",
                        },
                    ]}
                >
                    <Input.TextArea placeholder="请输入描述" maxLength={200} showCount>
                    </Input.TextArea>
                </FormItem>
            </Form>
        </Modal>
    </>
}

export { DemandStatus };

export default connect(({queryParams}) => ({
    queryInitParams: queryParams.demandPage,
}))(ProjectDemand);